import Vue from 'vue'
import Vuex from 'vuex'

// Vuex 是 Vue 的核心插件，调用 Vue.use() 来使用插件
Vue.use(Vuex)

let index = 4

// 创建 Store
const store = new Vuex.Store({
  state: {
    // 初始化各组件要共享用户到的状态数据
    todos: new Array(3).fill(null).map((v, i) => ({
      id: i + 1,
      title: '待办事项内容：' + (i + 1),
      completed: false
    }))
  },
  getters: {},
  mutations: {
    // mutation 方法，用于同步更新状态数据
    /**
     * 添加待办事项
     * @param {*} state state 状态数据
     * @param {*} payload 有效载荷，即要在添加待办事项时携带的有效数据
     */
    addTodoItem (state, payload) {
      state.todos.push({
        id: index++,
        title: payload.title,
        completed: false
      })
    },
    toggleTodoItem (state, payload) {
      state.todos = state.todos.map(todo => {
        const copy = { ...todo }
        if (copy.id === payload.id) {
          copy.completed = !copy.completed
        }
        return copy
      })
    },
    removeTodoItem (state, payload) {
      state.todos = state.todos.filter(todo => todo.id !== payload.id)
    }
  },
  actions: {},
  modules: {}
})

// 导出 store
export default store
